﻿using System;
using System.Collections.Concurrent;
using Zj.CourseManage.Domain.Events;

namespace Zj.CourseManage.Messaging.Simple
{
    /// <summary>
    /// Message queue
    /// </summary>
    public class MessageQueue
    {
        private readonly ConcurrentQueue<IEvent> _queue = new ConcurrentQueue<IEvent>();

        public event EventHandler<EventProcessedArgs> eventPushed;
        public MessageQueue()
        { }

        public void Push(IEvent @event)
        {
            _queue.Enqueue(@event);
            OnMessagePushed(new EventProcessedArgs(@event));
        }


        public IEvent Pop()
        {
            var succeeded = _queue.TryDequeue(out IEvent @event);
            return succeeded ? @event : null;
        }

        public int Count { get => this._queue.Count; }


        private void OnMessagePushed(EventProcessedArgs eventArgs)
        {
            this.eventPushed?.Invoke(this,eventArgs);
        }
    }
}
